class LearningAssistant {
    constructor() {
        this.apiKey = 'sk-abeb299645294ca198996ac4dc87baaf'; // 替换为你的实际API Key
        this.baseURL = 'https://api.deepseek.com/v1';
        this.currentFunction = 'explain';

        this.initializeEventListeners();
    }

    initializeEventListeners() {
        // 功能选择按钮
        document.querySelectorAll('.func-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.func-btn').forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.currentFunction = e.target.dataset.func;
                this.updatePlaceholder();
            });
        });

        // 提交按钮
        document.getElementById('submit-btn').addEventListener('click', () => {
            this.processUserInput();
        });
    }

    updatePlaceholder() {
        const input = document.getElementById('user-input');
        const placeholders = {
            explain: '请输入你想要理解的概念，比如："机器学习"、"量子物理"...',
            answer: '请输入你的问题，比如："如何计算圆的面积？"...',
            summarize: '请输入需要总结的文本内容...'
        };
        input.placeholder = placeholders[this.currentFunction];
    }

    async processUserInput() {
        const userInput = document.getElementById('user-input').value.trim();

        if (!userInput) {
            alert('请输入内容！');
            return;
        }

        this.showLoading();

        try {
            const response = await this.callDeepSeekAPI(userInput);
            this.displayResponse(response);
        } catch (error) {
            console.error('API调用错误:', error);
            this.displayResponse('抱歉，服务暂时不可用，请稍后重试。');
        }
    }

    async callDeepSeekAPI(userInput) {
        const prompts = {
            explain: `请用简单易懂的语言，以学长/学姐的口吻，向一个初学者解释以下概念，并举一个生活中的例子：${userInput}`,
            answer: `你是一个耐心的家教。请按步骤解答以下问题，并在最后总结核心知识点。问题：${userInput}`,
            summarize: `请将以下文本内容总结为不超过5个要点的清单，要求清晰明了：${userInput}`
        };

        const response = await fetch(`${this.baseURL}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.apiKey}`
            },
            body: JSON.stringify({
                model: 'deepseek-chat',
                messages: [
                    {
                        role: 'user',
                        content: prompts[this.currentFunction]
                    }
                ],
                temperature: 0.7,
                max_tokens: 2000
            })
        });

        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }

        const data = await response.json();
        return data.choices[0].message.content;
    }

    showLoading() {
        document.getElementById('loading').classList.remove('hidden');
        document.getElementById('ai-response').classList.add('hidden');
    }

    displayResponse(content) {
        document.getElementById('loading').classList.add('hidden');
        const responseElement = document.getElementById('ai-response');
        responseElement.textContent = content;
        responseElement.classList.remove('hidden');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LearningAssistant();
});